import echarts from 'echarts';
import DataLoad from './dataLoader'

let Chart;
Chart = {
  components: {},
  instances: {},
  project: {
    name: '未命名',
    describe: '',
    layout: []
  },
  current: {id: ''},
  index: 0,
  // 加载状态标识，无数据意义，用于逻辑控制
  status: {
    flag: 0
  },
  // name - 图形组件唯一标示， graph - 组件类
  register: function (name, graph) {
    this.components[name] = graph;
  },
  // 基础绘图方法
  init: function (option, id) {
    let myChart = echarts.init(document.getElementById(id));
    myChart.setOption(option);
    return myChart;
  },
  // d3js绘图方法
  initD3: function (Option, id, data) {
    let myChart = new Option.Graph(id);
    Option.data = data;
    myChart.draw();
    return myChart;
  },
  // 通用基础绘图方法
  draw (id, option, name, key, describe, url) {
    if (!name) {
      console.error('Graph type name must not be undefined.');
    }
    let graph = Chart.components[name];
    option = option || graph.getOption();
    let e = Chart.init(option, id);
    if (!(id in Chart.instances)) {
      Chart.instances[id] = {
        'key': 'graph' + Chart.index++,
        'describe': '',
        'url': ''
      }
    }
    Chart.instances[id]['name'] = graph.name;
    Chart.instances[id]['option'] = option;
    Chart.instances[id]['style'] = graph.getStyle(option);
    Chart.instances[id]['instance'] = e;
    if (key) Chart.instances[id]['key'] = key;
    if (describe) Chart.instances[id]['describe'] = describe;
    if (url) Chart.instances[id]['url'] = url;
  },
  update: function (id) {
    let graph = Chart.components[Chart.instances[id].name];
    graph.draw(id, Chart.instances[id].option);
    // Chart.init(Chart.instances[id].option, id);
  },
  // update: function (name, id) {
  //   config[name].id = id;
  //   let lib = config[name].lib || '';
  //   let option = Chart.instances[name].option;
  //   if (lib === 'd3js') {
  //     Chart.initD3(option, id);
  //   } else {
  //     Chart.init(option, id);
  //   }
  // },
  // reload: function (option, name, typeName) {
  //   Chart.ajaxData(config[name].url, config[name].param, function (rst) {
  //     Chart.dataLoad(option, typeName, rst.data, config[name]['dataLoader']);
  //     Chart.draw(option, name, typeName, rst.data);
  //   });
  // },
  dataLoad: DataLoad,
  ajaxData: function (key, data, _callbackS, _callbackE) {
    let cbkf = ((Math.random() * 1000).toFixed(0) + 1000).toString();
    $.ajax({
      type: 'GET',
      url: key,
      data: data,
      dataType: 'json',
      jsonpCallback: 'call1back' + cbkf + 'a',
      crossDomain: true,
      success: function (data) {
        if (_callbackS) _callbackS(data);
      },
      error: function (data) {
        if (_callbackE)_callbackE(data);
        alert('error');
      }
    });
  }
};

export default Chart;
